package source

import (
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"net/url"
	"sort"
	"strings"
	"time"
)

const (
	TencentAppid   = "1106931598"
	TencentAppKey  = "JTy7m3hREUbxkF54"
	TencentBaseUrl = "https://api.ai.qq.com/fcgi-bin/nlp/nlp_texttranslate"
)

type TencentData struct {
	Source_text string
	Target_text string
}

type TencentRespose struct {
	Ret  int
	Msg  string
	Data TencentData
}

// 腾讯源翻译
func TranslateTencent(q, fromType string) []string {
	var wordMeans []string
	//根据中英文判断返回值
	var toResult string
	if fromType != "zh" {
		toResult = "zh"
	} else {
		toResult = "en"
	}

	timestamp := fmt.Sprintf("%d", time.Now().Unix())
	randStr := GetRandomSalt()

	params := map[string]string{
		"app_id":     TencentAppid,
		"source":     fromType,
		"target":     toResult,
		"text":       q,
		"time_stamp": timestamp,
		"nonce_str":  randStr,
	}
	params["sign"] = getReqSign(params)
	var query string
	for k, v := range params {
		value := url.QueryEscape(v)
		query += fmt.Sprintf("%s=%s&", k, value)
	}

	url := TencentBaseUrl + "?" + query
	body, err := GetJson(url)
	if err != nil {
		fmt.Println("返回结果出错", err)
	}

	var r TencentRespose
	if err2 := json.Unmarshal(body, &r); err2 != nil {
		fmt.Println("返回结果出错", err2)
	}

	results := r.Data //获取翻译结果
	wordMeans = append(wordMeans, results.Target_text)

	return wordMeans
}

func getReqSign(params map[string]string) string {

	var keys []string
	for k := range params {
		keys = append(keys, k)
	}

	sort.Strings(keys)

	var sign string
	var str string
	for i := 0; i < len(keys); i++ {
		v := url.QueryEscape(params[keys[i]])
		str += fmt.Sprintf("%s=%s&", keys[i], v)
	}

	str += "app_key=" + TencentAppKey
	h := md5.New()
	h.Write([]byte(str))
	sign = hex.EncodeToString(h.Sum(nil))
	return strings.ToUpper(sign)
}
